package com.thunder.record_test.fragments;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.thunder.record_test.R;
import com.thunder.record_test.views.StereoWaveformView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.text.DecimalFormat;

/**
 * 录音Fragment，封装录音、播放和波形显示功能
 * 支持不同的音频源和单双声道配置
 */
public class RecordFragment extends Fragment {
    // 常量
    private static final int SAMPLE_RATE = 48000;
    
    // 声道配置常量
    private static final int CHANNEL_CONFIG_MONO = AudioFormat.CHANNEL_IN_MONO;
    private static final int CHANNEL_CONFIG_STEREO = AudioFormat.CHANNEL_IN_STEREO;
    private static final int CHANNEL_OUT_CONFIG_MONO = AudioFormat.CHANNEL_OUT_MONO;
    private static final int CHANNEL_OUT_CONFIG_STEREO = AudioFormat.CHANNEL_OUT_STEREO;
    
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    
    // SharedPreferences 常量
    private static final String PREFS_NAME = "RecordSettings";
    private static final String KEY_MAX_RECORD_TIME = "max_record_time_";
    private static final String KEY_CHANNEL_CONFIG = "channel_config_";
    
    // 最大录音时间选项（分钟）
    private static final int[] MAX_RECORD_TIMES = {1, 2, 5, 10, 30};
    private static final int DEFAULT_MAX_RECORD_TIME_INDEX = 2; // 默认选择5分钟

    // 参数
    private int audioSource;
    private String title;
    private String fileName;
    private int channelConfig; // 声道配置
    private int playbackChannelConfig; // 播放声道配置
    private boolean isStereo; // 是否为双声道
    private int maxRecordTimeIndex; // 最大录音时间索引
    private long maxRecordTimeMs; // 最大录音时间（毫秒）

    // UI组件
    private TextView tvTitle;
    private TextView tvProgress;
    private TextView tvGain;
    private TextView tvChannelParams;
    private Button btnRecord; // 合并后的录音按钮
    private Button btnPlay;
    private Button btnStopPlay; // 添加停止播放按钮
    private SeekBar seekBar;
    private SeekBar gainSeekBar;
    private StereoWaveformView waveformView;
    private Button btnChannelConfig; // 声道配置按钮
    private Button btnMaxRecordTime; // 最大录音时间按钮
    private TextView tvLeftChannel; // 左声道标识
    private TextView tvRightChannel; // 右声道标识
    private TextView tvMonoChannel; // 单声道标识
    private View channelIndicator; // 声道标识容器

    // 录音相关
    private AudioRecord audioRecord;
    private boolean isRecording = false;
    private File audioFile;
    private int bufferSize;
    private Handler handler = new Handler(Looper.getMainLooper());
    
    // 录音时间限制相关
    private Runnable recordTimeoutRunnable;

    // 播放相关
    private boolean isPlaying = false;
    private boolean isPaused = false; // 新增：标记播放是否暂停
    private AudioTrack audioTrack;
    private Runnable progressUpdater;
    private long totalDuration = 0;
    private long currentPosition = 0; // 新增：保存当前播放位置
    private FileInputStream fis; // 新增：保存文件输入流引用

    // 计时器
    private ScheduledExecutorService timerExecutor;
    private long startTime = 0;
    
    // 格式化器
    private DecimalFormat decimalFormat = new DecimalFormat("#0.0");
    
    // SharedPreferences
    private SharedPreferences sharedPreferences;

    /**
     * 创建新的录音Fragment实例
     * @param audioSource 音频源类型
     * @param title 标题
     * @param fileName 文件名
     * @return Fragment实例
     */
    public static RecordFragment newInstance(int audioSource, String title, String fileName) {
        RecordFragment fragment = new RecordFragment();
        Bundle args = new Bundle();
        args.putInt("audioSource", audioSource);
        args.putString("title", title);
        args.putString("fileName", fileName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            audioSource = getArguments().getInt("audioSource", MediaRecorder.AudioSource.MIC);
            title = getArguments().getString("title", "录音");
            fileName = getArguments().getString("fileName", "recording.pcm");
        }
        
        // 初始化SharedPreferences
        sharedPreferences = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_record, container, false);
        
        // 初始化UI
        tvTitle = view.findViewById(R.id.tvTitle);
        tvProgress = view.findViewById(R.id.tvProgress);
        tvGain = view.findViewById(R.id.tvGain);
        tvChannelParams = view.findViewById(R.id.tvChannelParams);
        btnRecord = view.findViewById(R.id.btnRecord);
        btnPlay = view.findViewById(R.id.btnPlay);
        btnStopPlay = view.findViewById(R.id.btnStopPlay); // 初始化停止按钮
        seekBar = view.findViewById(R.id.seekBar);
        gainSeekBar = view.findViewById(R.id.gainSeekBar);
        waveformView = view.findViewById(R.id.waveformView);
        btnChannelConfig = view.findViewById(R.id.btnChannelConfig);
        btnMaxRecordTime = view.findViewById(R.id.btnMaxRecordTime);
        tvLeftChannel = view.findViewById(R.id.tvLeftChannel);
        tvRightChannel = view.findViewById(R.id.tvRightChannel);
        tvMonoChannel = view.findViewById(R.id.tvMonoChannel);
        channelIndicator = view.findViewById(R.id.channelIndicator);
        
        // 设置标题
        tvTitle.setText(title);
        
        // 设置声道配置
        setupChannelConfig();
        
        // 设置通道参数信息
        setChannelParamsInfo();
        
        // 初始化音频
        initAudio();
        
        // 设置按钮事件
        setupButtons();
        
        // 设置进度条
        setupSeekBar();
        
        // 设置增益滑动条
        setupGainSeekBar();
        
        // 设置最大录音时间
        setupMaxRecordTime();
        
        // 确保初始按钮状态正确
        updateRecordButtonState();
        updatePlayButtonState();
        
        return view;
    }
    
    /**
     * 设置声道配置
     */
    private void setupChannelConfig() {
        // 获取保存的声道配置，默认根据音频源而定
        String prefKey = KEY_CHANNEL_CONFIG + audioSource;
        
        // 对于VOICE_RECOGNITION，默认强制使用单声道，因为该音频源仅支持单声道
        boolean defaultIsStereo = audioSource != MediaRecorder.AudioSource.VOICE_RECOGNITION;
        isStereo = sharedPreferences.getBoolean(prefKey, defaultIsStereo);
        
        // 如果是VOICE_RECOGNITION，则强制使用单声道并禁用选择
        if (audioSource == MediaRecorder.AudioSource.VOICE_RECOGNITION) {
            isStereo = false;
            btnChannelConfig.setEnabled(false);
            btnChannelConfig.setAlpha(0.5f);
        } else {
            btnChannelConfig.setEnabled(true);
            btnChannelConfig.setAlpha(1.0f);
        }
        
        // 更新按钮文本
        updateChannelConfigButtonText();
        
        // 设置正确的通道配置
        updateChannelConfig();
        
        // 设置按钮点击监听器
        btnChannelConfig.setOnClickListener(v -> {
            // 如果是VOICE_RECOGNITION，则忽略点击
            if (audioSource == MediaRecorder.AudioSource.VOICE_RECOGNITION) {
                Toast.makeText(requireContext(), 
                        "语音识别模式只支持单声道录音", 
                        Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 如果正在录音或播放，则不允许更改
            if (isRecording || isPlaying) {
                Toast.makeText(requireContext(), 
                        "录音或播放过程中不能更改声道配置", 
                        Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 显示声道配置对话框
            showChannelConfigDialog();
        });
    }
    
    /**
     * 显示声道配置对话框
     */
    private void showChannelConfigDialog() {
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("选择声道配置");
        
        // 设置单选项
        final String[] options = {"单声道", "双声道"};
        final int checkedItem = isStereo ? 1 : 0;
        
        builder.setSingleChoiceItems(options, checkedItem, (dialog, which) -> {
            boolean newIsStereo = (which == 1);
            
            // 如果选择有变化
            if (newIsStereo != isStereo) {
                isStereo = newIsStereo;
                
                // 保存设置到SharedPreferences
                String prefKey = KEY_CHANNEL_CONFIG + audioSource;
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean(prefKey, isStereo);
                editor.apply();
                
                // 更新通道配置
                updateChannelConfig();
                
                // 更新通道参数信息
                setChannelParamsInfo();
                
                // 更新按钮文本
                updateChannelConfigButtonText();
                
                // 重新初始化音频
                initAudio();
                
                Toast.makeText(requireContext(), 
                        "已设置声道为: " + options[which], 
                        Toast.LENGTH_SHORT).show();
            }
            
            dialog.dismiss();
        });
        
        builder.setNegativeButton("取消", null);
        
        // 显示对话框
        builder.create().show();
    }
    
    /**
     * 更新声道配置按钮文本
     */
    private void updateChannelConfigButtonText() {
        String channelText = isStereo ? "双声道" : "单声道";
        btnChannelConfig.setText("声道: " + channelText);
    }
    
    /**
     * 更新通道配置
     */
    private void updateChannelConfig() {
        if (isStereo) {
            channelConfig = CHANNEL_CONFIG_STEREO;
            playbackChannelConfig = CHANNEL_OUT_CONFIG_STEREO;
            // 更新波形视图的声道模式
            waveformView.setStereoMode(true);
            
            // 更新声道标识显示
            if (tvLeftChannel != null && tvRightChannel != null && tvMonoChannel != null) {
                tvLeftChannel.setVisibility(View.VISIBLE);
                tvRightChannel.setVisibility(View.VISIBLE);
                tvMonoChannel.setVisibility(View.GONE);
            }
        } else {
            channelConfig = CHANNEL_CONFIG_MONO;
            playbackChannelConfig = CHANNEL_OUT_CONFIG_MONO;
            // 更新波形视图的声道模式
            waveformView.setStereoMode(false);
            
            // 更新声道标识显示
            if (tvLeftChannel != null && tvRightChannel != null && tvMonoChannel != null) {
                tvLeftChannel.setVisibility(View.GONE);
                tvRightChannel.setVisibility(View.GONE);
                tvMonoChannel.setVisibility(View.VISIBLE);
            }
        }
    }
    
    /**
     * 设置最大录音时间选项
     */
    private void setupMaxRecordTime() {
        // 从SharedPreferences加载保存的设置
        String prefKey = KEY_MAX_RECORD_TIME + audioSource; // 为不同音频源保存不同设置
        maxRecordTimeIndex = sharedPreferences.getInt(prefKey, DEFAULT_MAX_RECORD_TIME_INDEX);
        
        // 更新最大录音时间（毫秒）
        maxRecordTimeMs = MAX_RECORD_TIMES[maxRecordTimeIndex] * 60 * 1000;
        
        // 更新按钮文本
        updateMaxRecordTimeButtonText();
        
        // 设置按钮点击监听器
        btnMaxRecordTime.setOnClickListener(v -> {
            // 如果正在录音或播放，则不允许更改
            if (isRecording || isPlaying) {
                Toast.makeText(requireContext(), 
                        "录音或播放过程中不能更改最大录音时间", 
                        Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 显示最大录音时间对话框
            showMaxRecordTimeDialog();
        });
    }
    
    /**
     * 显示最大录音时间对话框
     */
    private void showMaxRecordTimeDialog() {
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("选择最大录音时长");
        
        // 设置单选项
        final String[] options = {"1分钟", "2分钟", "5分钟", "10分钟", "30分钟"};
        
        builder.setSingleChoiceItems(options, maxRecordTimeIndex, (dialog, which) -> {
            // 更新最大录音时间索引
            maxRecordTimeIndex = which;
            maxRecordTimeMs = MAX_RECORD_TIMES[maxRecordTimeIndex] * 60 * 1000;
            
            // 保存设置到SharedPreferences
            String prefKey = KEY_MAX_RECORD_TIME + audioSource;
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt(prefKey, maxRecordTimeIndex);
            editor.apply();
            
            // 更新按钮文本
            updateMaxRecordTimeButtonText();
            
            Toast.makeText(requireContext(), 
                    "已设置最大录音时间: " + options[which], 
                    Toast.LENGTH_SHORT).show();
            
            dialog.dismiss();
        });
        
        builder.setNegativeButton("取消", null);
        
        // 显示对话框
        builder.create().show();
    }
    
    /**
     * 更新最大录音时间按钮文本
     */
    private void updateMaxRecordTimeButtonText() {
        btnMaxRecordTime.setText("录音时长: " + MAX_RECORD_TIMES[maxRecordTimeIndex] + "分钟");
    }
    
    /**
     * 设置通道参数信息
     */
    private void setChannelParamsInfo() {
        String audioSourceName = getAudioSourceName(audioSource);
        String channelConfig = isStereo ? "双声道" : "单声道";
        String formatStr = (AUDIO_FORMAT == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit PCM" : "其他格式";
        
        String params = String.format("音频源: %s | 采样率: %d Hz | 通道: %s | 格式: %s", 
                audioSourceName, SAMPLE_RATE, channelConfig, formatStr);
        
        tvChannelParams.setText(params);
    }
    
    /**
     * 获取音频源名称
     * @param source 音频源常量
     * @return 音频源名称
     */
    private String getAudioSourceName(int source) {
        switch (source) {
            case MediaRecorder.AudioSource.MIC:
                return "麦克风";
            case MediaRecorder.AudioSource.VOICE_RECOGNITION:
                return "语音识别专用";
            case MediaRecorder.AudioSource.VOICE_COMMUNICATION:
                return "语音通话";
            case MediaRecorder.AudioSource.CAMCORDER:
                return "摄像机";
            case MediaRecorder.AudioSource.DEFAULT:
                return "默认";
            default:
                return "未知(" + source + ")";
        }
    }

    private void initAudio() {
        bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, channelConfig, AUDIO_FORMAT);
        
        // 确保拥有录音权限
        if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
            audioRecord = new AudioRecord(audioSource, SAMPLE_RATE, channelConfig, AUDIO_FORMAT, bufferSize);
        }
    }

    private void setupButtons() {
        // 录音按钮 - 根据状态切换功能
        btnRecord.setOnClickListener(v -> {
            if (isRecording) {
                stopRecording();
            } else {
                startRecording();
            }
        });
        
        // 播放按钮 - 根据状态切换功能
        btnPlay.setOnClickListener(v -> {
            if (isPlaying) {
                if (isPaused) {
                    resumePlaying(); // 继续播放
                } else {
                    pausePlaying(); // 暂停播放
                }
            } else {
                playRecording(); // 开始播放
            }
        });
        
        // 停止播放按钮
        btnStopPlay.setOnClickListener(v -> {
            if (isPlaying) {
                stopPlaying();
            }
        });
        
        // 初始化播放按钮状态
        updatePlayButtonState();
    }

    private void setupSeekBar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && audioTrack != null) {
                    int targetPosition = (int) (progress * totalDuration / 1000);
                    audioTrack.pause();
                    audioTrack.flush();
                    // 这里应该有seek逻辑，但简单播放不需要
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    /**
     * 设置增益滑动条
     */
    private void setupGainSeekBar() {
        // 初始化增益显示
        updateGainText(0.0f);
        
        gainSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 将progress (0-10) 映射到增益范围 (-5 to 5)
                float gain = (progress - 5) * 1.0f;
                waveformView.setAmplitudeGain(gain);
                updateGainText(gain);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        
        // 设置默认值为中间值
        gainSeekBar.setProgress(5);
    }
    
    /**
     * 更新增益显示文本
     * @param gain 增益值
     */
    private void updateGainText(float gain) {
        tvGain.setText(decimalFormat.format(gain));
    }

    private void startRecording() {
        if (audioRecord == null) {
            Toast.makeText(requireContext(), "音频设备初始化失败", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            // 创建录音文件
            File dir = requireContext().getExternalFilesDir(Environment.DIRECTORY_MUSIC);
            audioFile = new File(dir, fileName);
            
            if (audioFile.exists()) {
                audioFile.delete();
                audioFile.createNewFile();
            }
            
            isRecording = true;
            audioRecord.startRecording();
            
            // 清除之前的波形
            waveformView.clear();
            
            // 启动录音线程
            new Thread(() -> writeAudioDataToFile()).start();
            
            // 更新UI
            updateRecordButtonState();
            
            // 禁用回放相关按钮
            requireActivity().runOnUiThread(() -> {
                // 禁用播放按钮
                btnPlay.setEnabled(false);
                btnPlay.setAlpha(0.5f);
                
                // 禁用停止播放按钮
                btnStopPlay.setEnabled(false);
                btnStopPlay.setAlpha(0.5f);
                
                // 禁用配置按钮
                btnChannelConfig.setEnabled(false);
                btnChannelConfig.setAlpha(0.5f);
                btnMaxRecordTime.setEnabled(false);
                btnMaxRecordTime.setAlpha(0.5f);
            });
            
            // 开始计时
            startTime = System.currentTimeMillis();
            startTimer();
            
            // 设置录音超时
            scheduleRecordingTimeout();
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "录音启动失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 设置录音超时定时器
     */
    private void scheduleRecordingTimeout() {
        // 移除之前的超时任务
        if (recordTimeoutRunnable != null) {
            handler.removeCallbacks(recordTimeoutRunnable);
        }
        
        // 创建新的超时任务
        recordTimeoutRunnable = () -> {
            if (isRecording) {
                // 达到最大时间，停止录音
                Toast.makeText(requireContext(), 
                        "已达到最大录音时间: " + MAX_RECORD_TIMES[maxRecordTimeIndex] + "分钟", 
                        Toast.LENGTH_SHORT).show();
                stopRecording();
            }
        };
        
        // 设置超时任务
        handler.postDelayed(recordTimeoutRunnable, maxRecordTimeMs);
    }

    private void writeAudioDataToFile() {
        try (FileOutputStream fos = new FileOutputStream(audioFile)) {
            byte[] buffer = new byte[bufferSize];
            while (isRecording) {
                int read = audioRecord.read(buffer, 0, bufferSize);
                if (read != AudioRecord.ERROR_INVALID_OPERATION) {
                    fos.write(buffer, 0, read);
                    
                    // 更新波形显示
                    updateWaveform(buffer, read);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateWaveform(byte[] buffer, int bufferSize) {
        requireActivity().runOnUiThread(() -> {
            waveformView.addAudioData(buffer, bufferSize);
        });
    }

    private void stopRecording() {
        isRecording = false;
        if (audioRecord != null) {
            audioRecord.stop();
        }
        
        // 移除录音超时任务
        if (recordTimeoutRunnable != null) {
            handler.removeCallbacks(recordTimeoutRunnable);
        }
        
        // 更新UI
        updateRecordButtonState();
        updatePlayButtonState();
        
        // 重新启用配置按钮，VOICE_RECOGNITION仍然禁用声道选择
        requireActivity().runOnUiThread(() -> {
            // 声道配置按钮
            if (audioSource != MediaRecorder.AudioSource.VOICE_RECOGNITION) {
                btnChannelConfig.setEnabled(true);
                btnChannelConfig.setAlpha(1.0f);
            }
            
            // 最大录音时间按钮
            btnMaxRecordTime.setEnabled(true);
            btnMaxRecordTime.setAlpha(1.0f);
        });
        
        Toast.makeText(requireContext(), "录音已保存", Toast.LENGTH_SHORT).show();
        stopTimer();
    }
    
    /**
     * 更新录音按钮状态
     */
    private void updateRecordButtonState() {
        requireActivity().runOnUiThread(() -> {
            // 录音状态切换
            if (isRecording) {
                btnRecord.setText("停止录音 (00:00)");
                btnRecord.setBackgroundTintList(ContextCompat.getColorStateList(requireContext(), android.R.color.holo_red_light));
            } else {
                btnRecord.setText("开始录音");
                btnRecord.setBackgroundTintList(ContextCompat.getColorStateList(requireContext(), android.R.color.holo_green_light));
            }
            
            // 在回放时禁用录音按钮
            btnRecord.setEnabled(!isPlaying);
            
            // 根据禁用状态设置Alpha值，使按钮在禁用时显示灰色
            if (!btnRecord.isEnabled()) {
                btnRecord.setAlpha(0.5f);
            } else {
                btnRecord.setAlpha(1.0f);
            }
        });
    }

    /**
     * 更新播放按钮状态
     */
    private void updatePlayButtonState() {
        boolean fileExists = audioFile != null && audioFile.exists();
        requireActivity().runOnUiThread(() -> {
            // 回放状态切换
            if (isPlaying) {
                btnPlay.setText(isPaused ? "继续播放" : "暂停播放");
                btnStopPlay.setEnabled(true);  // 启用停止按钮
            } else {
                btnPlay.setText("回放录音");
                btnStopPlay.setEnabled(false); // 禁用停止按钮
            }
            
            // 只有在不录音且有文件的情况下启用回放按钮
            boolean canPlay = fileExists && !isRecording;
            btnPlay.setEnabled(canPlay);
            
            // 根据禁用状态设置Alpha值
            if (!btnPlay.isEnabled()) {
                btnPlay.setAlpha(0.5f);
            } else {
                btnPlay.setAlpha(1.0f);
            }
            
            if (!btnStopPlay.isEnabled()) {
                btnStopPlay.setAlpha(0.5f);
            } else {
                btnStopPlay.setAlpha(1.0f);
            }
        });
    }

    private void playRecording() {
        if (audioFile == null || !audioFile.exists()) {
            Toast.makeText(requireContext(), "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        isPlaying = true;
        isPaused = false; // 重置暂停状态
        updatePlayButtonState();
        updateRecordButtonState();
        
        // 禁用配置按钮
        requireActivity().runOnUiThread(() -> {
            btnChannelConfig.setEnabled(false);
            btnChannelConfig.setAlpha(0.5f);
            btnMaxRecordTime.setEnabled(false);
            btnMaxRecordTime.setAlpha(0.5f);
        });
        
        // 播放时清除波形
        waveformView.clear();
        
        new Thread(() -> {
            FileInputStream localFis = null;
            try {
                localFis = new FileInputStream(audioFile);
                // 保存到成员变量，确保所有线程都能安全访问最新的引用
                fis = localFis;
                
                audioTrack = new AudioTrack(
                        android.media.AudioManager.STREAM_MUSIC,
                        SAMPLE_RATE,
                        playbackChannelConfig,
                        AUDIO_FORMAT,
                        bufferSize,
                        AudioTrack.MODE_STREAM);
                
                // 根据声道数计算每个采样的字节数
                int bytesPerSample = 2; // 16bit = 2 bytes
                int bytesPerFrame = isStereo ? bytesPerSample * 2 : bytesPerSample;
                final long totalFrames = audioFile.length() / bytesPerFrame;
                
                totalDuration = (totalFrames * 1000 / SAMPLE_RATE);
                seekBar.setMax((int) totalDuration);
                
                audioTrack.play();
                
                // 进度更新任务
                progressUpdater = new Runnable() {
                    @Override
                    public void run() {
                        if (audioTrack != null && isPlaying) {
                            int position = audioTrack.getPlaybackHeadPosition();
                            currentPosition = (int) (position * 1000 / SAMPLE_RATE);
                            
                            requireActivity().runOnUiThread(() -> {
                                seekBar.setProgress((int)currentPosition);
                                tvProgress.setText(formatTime((int)currentPosition) + " / " + formatTime((int) totalDuration));
                            });
                            
                            if (!isPaused) {
                                handler.postDelayed(this, 200);
                            }
                        }
                    }
                };
                handler.post(progressUpdater);

                byte[] buffer = new byte[bufferSize];
                int read;
                
                // 确保只有在isPlaying为true且fis不为null时继续读取数据
                // 在每次循环中检查fis是否为null，防止在停止期间出现空指针
                while (isPlaying && (fis != null) && (read = fis.read(buffer)) != -1) {
                    if (isPaused) {
                        // 暂停状态，等待恢复
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        // 重新检查状态，避免暂停中被停止后继续执行
                        if (!isPlaying || fis == null) {
                            break;
                        }
                    } else {
                        if (audioTrack != null) {
                            audioTrack.write(buffer, 0, read);
                        }
                        
                        // 播放时也显示波形
                        updateWaveform(buffer, read);
                    }
                }
                
                if (isPlaying) { // 如果是正常播放结束
                    stopPlaying();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 确保在线程结束前资源都被释放
                if (isPlaying) {
                    stopPlaying();
                }
            }
        }).start();
    }

    /**
     * 暂停播放
     */
    private void pausePlaying() {
        if (audioTrack != null && isPlaying) {
            isPaused = true;
            audioTrack.pause();
            updatePlayButtonState();
        }
    }

    /**
     * 继续播放
     */
    private void resumePlaying() {
        if (audioTrack != null && isPlaying && isPaused) {
            isPaused = false;
            audioTrack.play();
            handler.post(progressUpdater);
            updatePlayButtonState();
        }
    }

    private void stopPlaying() {
        // 先标记状态，确保工作线程会退出
        isPlaying = false;
        isPaused = false;
        
        // 先保存引用，避免多线程环境下出现并发问题
        AudioTrack track = audioTrack;
        audioTrack = null;
        
        // 创建临时变量保存FileInputStream引用
        FileInputStream tempFis = fis;
        // 立即清除共享变量引用，防止其他线程继续使用
        fis = null;
        
        // 使用临时引用释放AudioTrack
        if (track != null) {
            try {
                track.stop();
                track.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        // 使用临时引用关闭文件流
        if (tempFis != null) {
            try {
                tempFis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        // 移除回调
        if (progressUpdater != null) {
            handler.removeCallbacks(progressUpdater);
        }
        
        // 所有UI操作都放在UI线程中执行
        requireActivity().runOnUiThread(() -> {
            // 更新UI
            updatePlayButtonState();
            updateRecordButtonState();
            
            // 重新启用设置按钮
            if (audioSource != MediaRecorder.AudioSource.VOICE_RECOGNITION) {
                btnChannelConfig.setEnabled(true);
                btnChannelConfig.setAlpha(1.0f);
            }
            btnMaxRecordTime.setEnabled(true);
            btnMaxRecordTime.setAlpha(1.0f);
            
            tvProgress.setText("00:00 / 00:00");
            seekBar.setProgress(0);
        });
    }

    private void startTimer() {
        stopTimer();
        timerExecutor = Executors.newSingleThreadScheduledExecutor();
        timerExecutor.scheduleAtFixedRate(() -> {
            long elapsed = System.currentTimeMillis() - startTime;
            String timeString = formatTime((int) elapsed);
            requireActivity().runOnUiThread(() -> {
                if (isRecording) {
                    btnRecord.setText("停止录音 (" + timeString + ")");
                }
            });
        }, 0, 200, TimeUnit.MILLISECONDS);
    }

    private void stopTimer() {
        if (timerExecutor != null && !timerExecutor.isShutdown()) {
            timerExecutor.shutdownNow();
        }
    }

    private String formatTime(int milliseconds) {
        int seconds = milliseconds / 1000;
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        if (audioTrack != null) {
            audioTrack.release();
            audioTrack = null;
        }
        stopTimer();
        handler.removeCallbacksAndMessages(null);
    }
} 